package com.ja.openchat.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.chat.ForwardActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.contact.ContactDetailSingleActivity;
import com.ja.openchat.ui.dialog.CheckChatInviteLinkDialog;
import com.ja.openchat.ui.login.LoginActivity;
import com.ja.openchat.views.BottomAddGroupDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.ChatInviteLink;
import com.zy.openchat.core.model.group.RequestData;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.FileUtils;

import java.util.Map;

public class OuterShareActivity extends AppCompatActivity {

    public static boolean isStartMain = false;
    public static boolean isStartSplash = false;

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntent(getIntent());
    }

    private void handleIntent(Intent intent){
        if(intent==null){
            SplashActivity.start(this);
            return;
        }
        boolean isNeedFinish = true;
        if(isStartMain){
            isNeedFinish = handleOuterIntent(this,intent);
        } else if(isStartSplash){
            startActivity(new Intent(this, LoginActivity.class));
        } else{
            SplashActivity.start(this,intent.getAction(),intent.getExtras(),intent.getData());
        }
        if(isNeedFinish){
            finish();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    public static boolean handleShareIntent(Activity context, Intent itnIn){
        if(itnIn==null){
            return true;
        }
        Bundle extras = itnIn.getExtras();
        String action = itnIn.getAction();
        if (Intent.ACTION_SEND.equals(action)) {
            if(extras.containsKey(Intent.EXTRA_STREAM)){
                Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
                String path = FileUtils.getPath(context, uri);
                if(!TextUtils.isEmpty(path)){
                    Intent intent = new Intent(context, ForwardActivity.class);
                    intent.putExtra(ForwardActivity.BUNDLE_OUTER_PATH,path);
                    context.startActivity(intent);
                }
            }else if(extras.containsKey(Intent.EXTRA_TEXT)){
                String content = extras.getString(Intent.EXTRA_TEXT);
                if(!TextUtils.isEmpty(content)){
                    Intent intent = new Intent(context, ForwardActivity.class);
                    intent.putExtra(ForwardActivity.BUNDLE_OUTER_TEXT,content);
                    context.startActivity(intent);
                }
            }
        }
        return true;
    }

    public static boolean handleViewIntent(FragmentActivity context, Intent itnIn){
        if(itnIn==null){
            return true;
        }
        Bundle extras = itnIn.getExtras();
        String action = itnIn.getAction();
        if(Intent.ACTION_VIEW.equals(itnIn.getAction())){
            Uri data = itnIn.getData();
            String outerScheme = Common.getMetaDataByKey("outerScheme");
            outerScheme = TextUtils.isEmpty(outerScheme)?"openchat":outerScheme;
            if(!outerScheme.equals(itnIn.getScheme())){
//                String shareInstallScheme = Common.getMetaDataByKey("shareInstallScheme");
//                if(!TextUtils.isEmpty(shareInstallScheme)&&shareInstallScheme.equals(itnIn.getScheme())){
//                    ShareInstall.getInstance().getWakeUpParams(itnIn, new AppGetWakeUpListener() {
//                        @Override
//                        public void onGetWakeUpFinish(String info) {
//                            // 客户端获取到的参数是json字符串格式
//                            Log.d("ShareInstall", "info = " + info);
//                            try {
//                                JSONObject object = new JSONObject(info);
//                                // 通过该方法拿到设置的渠道值，剩余值为自定义的其他参数
//                                String channel = object.optString("channel");
//                                Log.d("ShareInstall", "channel = " + channel);
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });
//                    return false;
//                }
                return true;
            }
            if(data!=null&&!TextUtils.isEmpty(data.getQueryParameter("uid"))){
                if(TelegramManager.getTelegramManager().getTgData().getUserConnectionState() != TelegramManager.GoUserConnectionState.GoUserConnectionState_StateReady){
                    if(context instanceof MainActivity){

                    }else{
                        MainActivity.start(context,itnIn.getAction(),itnIn.getExtras(),itnIn.getData());
                    }

                    return true;
                }
                String encryUid = data.getQueryParameter("uid");
                String uid = UserInfo.decryptString(encryUid);
                long userId = 0;
                try {
                    userId = Long.parseLong(uid);
                }catch (Exception e){
                    e.printStackTrace();
                }
                TelegramManager.getTelegramManager().requestContactInfo(context, userId, new TgResultBlock<UserInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {
                        if (obj != null) {
//                            ContactDetailActivity.start(context, obj);
                            ContactDetailSingleActivity.start(context, obj);
                        } else {
                            ToastUtils.showShort(context.getString(R.string.request_error));
                        }
                        if(context instanceof OuterShareActivity){
                            ((OuterShareActivity)context).finish();
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        ToastUtils.showShort(context.getString(R.string.request_error));
                        if(context instanceof OuterShareActivity){
                            ((OuterShareActivity)context).finish();
                        }
                    }
                });
                return false;
            }else if(data!=null&&(!TextUtils.isEmpty(data.getQueryParameter("link"))||data.toString().contains("link"))){
                if(TelegramManager.getTelegramManager().getTgData().getUserConnectionState() != TelegramManager.GoUserConnectionState.GoUserConnectionState_StateReady){
                    if(context instanceof MainActivity){

                    }else{
                        MainActivity.start(context,itnIn.getAction(),itnIn.getExtras(),itnIn.getData());
                    }
                    return true;
                }
                String link;
                if(!TextUtils.isEmpty(data.getQueryParameter("link"))){
                    link = data.getQueryParameter("link");
                }else{
                    link = data.toString().substring(data.toString().indexOf("link=")+"link=".length());
                }
                handleOuterInviteLink(context,link);
                return false;
            }
        }
        return true;
    }


    private static void showCheckChatInviteLinkDialog(FragmentActivity context,ChatInviteLink data){
        new XPopup.Builder(context)
                .setPopupCallback(new SimpleCallback(){
                    @Override
                    public void onDismiss(BasePopupView popupView) {
                        super.onDismiss(popupView);
                        if(context instanceof OuterShareActivity){
                            ((OuterShareActivity)context).finish();
                        }
                    }
                })
                .asCustom(new CheckChatInviteLinkDialog(context, data))
                .show();
    }


    private static void showBottomAddGroupDialog(FragmentActivity context,final ChatInfo chatInfo){
        new XPopup.Builder(context)
                .hasShadowBg(true)
                .atView(context.getCurrentFocus())
                .asCustom(new BottomAddGroupDialog(context, chatInfo, new BottomAddGroupDialog.OnItemClickListner() {
                    @Override
                    public void clickPostion(int postion, ChatInfo chatInfo) {
                        switch (postion) {
                            case 0://跳转
                                ChatActivity.startActivity(context,chatInfo);
                                break;
                            case 1://取消
                                break;
                        }
                    }
                })).show();
    }

    public static void handleOuterInviteLink(FragmentActivity context,String link){
        String invite_link = Constants.GROUP_SHARE_LINK_PRE_TEXT+link;
        TelegramManager.getTelegramManager().checkChatInviteLink(context, invite_link, false,new TgResultBlock<RequestData<ChatInviteLink>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response,final RequestData<ChatInviteLink> obj) {
                if (obj != null&&obj.isOk&&obj.data!=null) {
                    obj.data.invite_link = invite_link;
                    if(obj.data.type!=null&&"chatTypeSupergroup".equals(obj.data.type.type)){
                        TelegramManager.getTelegramManager().getSuperGroupInfo(context, obj.data.type.supergroup_id, new TgResultBlock<SuperGroupInfo>() {
                            @Override
                            public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo superGroupInfo) {
                                if(superGroupInfo!=null&&superGroupInfo.isMyGroup()){
                                    TelegramManager.getTelegramManager().requestChatInfoByChatId(context, obj.data.chat_id, new TgResultBlock<ChatInfo>() {
                                        @Override
                                        public void onResult(Map<String, Object> request, JsonObject response, ChatInfo chatInfo) {
                                            ChatActivity.startActivity(context,chatInfo);
                                        }

                                        @Override
                                        public void onTimeout(Map<String, Object> request) {
                                            showCheckChatInviteLinkDialog(context,obj.data);
                                        }
                                    });
                                }else{
                                    showCheckChatInviteLinkDialog(context,obj.data);
                                }
                            }

                            @Override
                            public void onTimeout(Map<String, Object> request) {
                                showCheckChatInviteLinkDialog(context,obj.data);
                            }
                        });
                    }else{
                        showCheckChatInviteLinkDialog(context,obj.data);
                    }

                } else if(obj!=null&&obj.data!=null&&obj.data.chatInfo!=null){
                    if(obj.data.chatInfo.isSuperGroup() || obj.data.chatInfo.isGroup()){
                        if(obj.data.chatInfo.isSuperGroup()){
                            TelegramManager.getTelegramManager().getSuperGroupInfo(context, obj.data.type.supergroup_id, new TgResultBlock<SuperGroupInfo>() {
                                @Override
                                public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo superGroupInfo) {
                                    if(superGroupInfo!=null&&superGroupInfo.isMyGroup()){
                                        ChatActivity.startActivity(context,obj.data.chatInfo);
                                        if(context instanceof OuterShareActivity){
                                            ((OuterShareActivity)context).finish();
                                        }
                                    }else{
                                        showBottomAddGroupDialog(context,obj.data.chatInfo);
                                    }
                                }

                                @Override
                                public void onTimeout(Map<String, Object> request) {
                                    showBottomAddGroupDialog(context,obj.data.chatInfo);
                                }
                            });
                        }else{
                            showBottomAddGroupDialog(context,obj.data.chatInfo);
                        }

                    }
                } else if(obj != null&&!TextUtils.isEmpty(obj.errorMsg)){
                    ToastUtils.showShort(obj.errorMsg);
                }else {
                    ToastUtils.showShort(context.getString(R.string.invalid_group_link));
                    if(context instanceof OuterShareActivity){
                        ((OuterShareActivity)context).finish();
                    }
                }

            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                ToastUtils.showShort(context.getString(R.string.request_error));

            }
        });
    }

    public static boolean handleOuterIntent(FragmentActivity context, Intent itnIn){
        if(itnIn==null){
            return true;
        }
        Bundle extras = itnIn.getExtras();
        String action = itnIn.getAction();
        if (Intent.ACTION_SEND.equals(action)) {
            return handleShareIntent(context,itnIn);
        }else if(Intent.ACTION_VIEW.equals(itnIn.getAction())){
            return handleViewIntent(context, itnIn);
        }
        return true;
    }
}
